package com.example.messagemodule.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.PermissionChecker;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.examination.mlib.manager.PermissionManager;
import com.example.messagemodule.R;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.PathUtil;
import com.lebanban.mp3library.MP3Recorder;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("AppCompatCustomView")
public class TalkingButton extends Button {

    private static PopupWindow voicePopWindow;
    private View voiceView;
    private static ImageView messageVoiceCancel;
    private static ImageView messageVoiceTotext;
    private static ImageView messageVoiceBottomBg;
    private static TextView messageVoiceCancelTitle;
    private static TextView messageVoiceTotextTitle;
    private static TextView messageVoiceBottomTitle;
    private static LinearLayout messageVoiceTotextModule;
    private static LinearLayout messageVoiceTovoiceModule;
    public LinearLayout messageVoiceTotextCancel;
    public LinearLayout messageVoiceTotextSendvoice;
    public static ImageView messageVoiceTotextText;
    private static ImageView messageVoiceBottomBgIcon;
    private static MessageVoiceBackgroundRedLeft messageVoiceCancelBg;
    public static MessageVoiceBackgroundGreenRight messageVoiceTotextBg;
    public static MessageVoiceBackgroundRedRight messageVoiceTexterrorBg;
    private static MessageVoiceBackgroundGreen messageVoiceSendvoiceBg;
    public static AudioWaveView audiowaveview;
    public static EditText messageVoiceTotextContent;
    public static TextView messageVoiceTotextUpdata;


    private static float X;
    private static float Y;

    public TalkingButton(Context context) {
        super(context);
        init(context);
        setOnTouchListener(new TalkingTouchListener());
    }

    public TalkingButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
        setOnTouchListener(new TalkingTouchListener());
    }

    public TalkingButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
        setOnTouchListener(new TalkingTouchListener());
    }

    private void init(Context context) {
        voicePopWindow = new PopupWindow();
        voiceView = LayoutInflater.from(context).inflate(R.layout.message_voice_popwindow, null);
        messageVoiceCancel = (ImageView) voiceView.findViewById(R.id.message_voice_cancel);
        messageVoiceTotext = (ImageView) voiceView.findViewById(R.id.message_voice_totext);
        messageVoiceBottomBg = (ImageView) voiceView.findViewById(R.id.message_voice_bottom_bg);
        messageVoiceCancelTitle = (TextView) voiceView.findViewById(R.id.message_voice_cancel_title);
        messageVoiceTotextTitle = (TextView) voiceView.findViewById(R.id.message_voice_totext_title);
        messageVoiceBottomTitle = (TextView) voiceView.findViewById(R.id.message_voice_bottom_title);
        messageVoiceTotextModule = (LinearLayout) voiceView.findViewById(R.id.message_voice_totext_module);
        messageVoiceTovoiceModule = (LinearLayout) voiceView.findViewById(R.id.message_voice_tovoice_module);
        messageVoiceTotextCancel = (LinearLayout) voiceView.findViewById(R.id.message_voice_totext_cancel);
        messageVoiceTotextSendvoice = (LinearLayout) voiceView.findViewById(R.id.message_voice_totext_sendvoice);
        messageVoiceTotextText = (ImageView) voiceView.findViewById(R.id.message_voice_totext_text);
        messageVoiceBottomBgIcon = (ImageView) voiceView.findViewById(R.id.message_voice_bottom_bg_icon);
        messageVoiceCancelBg = (MessageVoiceBackgroundRedLeft) voiceView.findViewById(R.id.message_voice_cancel_bg);
        messageVoiceTotextBg = (MessageVoiceBackgroundGreenRight) voiceView.findViewById(R.id.message_voice_totext_bg);
        messageVoiceTexterrorBg = (MessageVoiceBackgroundRedRight) voiceView.findViewById(R.id.message_voice_texterror_bg);
        messageVoiceSendvoiceBg = (MessageVoiceBackgroundGreen) voiceView.findViewById(R.id.message_voice_sendvoice_bg);
        audiowaveview = (AudioWaveView) voiceView.findViewById(R.id.audiowaveview);
        messageVoiceTotextContent = (EditText) voiceView.findViewById(R.id.message_voice_totext_content);
        messageVoiceTotextUpdata = (TextView) voiceView.findViewById(R.id.message_voice_totext_updata);

        Glide.with(this).load(R.drawable.message_voice_cancel).into(messageVoiceCancel);
        Glide.with(this).load(R.drawable.message_voice_totext).into(messageVoiceTotext);
        messageVoiceBottomBg.setBackground(getResources().getDrawable(R.drawable.message_voice_bottom_bg));
//        Glide.with(this).load(R.drawable.message_voice_bottom_bg).transform(new CenterCrop()).into(messageVoiceBottomBg);
        Glide.with(this).load(R.drawable.message_voice_totext_ing).transform(new CenterCrop(),new CircleCrop()).into(messageVoiceTotextText);
        voicePopWindow.setFocusable(true);
        voicePopWindow.setOutsideTouchable(false);
        voicePopWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        voicePopWindow.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
        voicePopWindow.setContentView(voiceView);


        messageVoiceTotextCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                voicePopWindow.dismiss();
            }
        });


    }

    private static TouchCallback touchCallback;

    public void setOnTouchListener(OnTouchListener l, TouchCallback touchCallback) {
        super.setOnTouchListener(l);
        this.touchCallback = touchCallback;
    }

    public void setOnClickListener(@Nullable OnClickListener l,TouchCallback touchCallback) {
        super.setOnClickListener(l);
        touchCallback.onSuccess(voicePath,voiceLength);
    }


    public void dismissTalkingButtonPop(){
        if (voicePopWindow!=null){
            voicePopWindow.dismiss();
        }
    }

//    private View.OnClickListener onSendVoiceClickListener;
//
//    public void setOnSendVoiceClickListener(View.OnClickListener onSendVoiceClickListener){
//        this.onSendVoiceClickListener = onSendVoiceClickListener;
//    }
//
//    private View.OnClickListener onSendTxtClickListener;
//
//    public void setOnSendTxtClickListener(View.OnClickListener SendTxtClickListener){
//        this.onSendTxtClickListener = SendTxtClickListener;
//    }

    private static String voicePath = null;
    private static int voiceLength = 0;
    private static MP3Recorder mp3Recorder = null;
    static long startTime = 0;
    private static Timer timer;
    public static class TalkingTouchListener implements OnTouchListener {
        private Handler handler = new Handler(Looper.getMainLooper());
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Boolean flag = PermissionChecker.checkSelfPermission(v.getContext(), Manifest.permission.RECORD_AUDIO) == PermissionChecker.PERMISSION_GRANTED;
            if (!flag) {
                PermissionManager.getInstance()
                        .get(v.getContext())
                        .requestPermissions(
                                new String[]{Manifest.permission.RECORD_AUDIO}
                                ,
                                new String[]{"允许应用使用录音权限"})
                        .requestCodes(0xa1)
                        .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
                            @Override
                            public void noM() {
                            }

                            @Override
                            public void granted() {
                            }

                            @Override
                            public void denied() {
                                ToastUtils.showShort("请允许应用使用录音权限");
                            }
                        })
                        .request();
                return false;
            }
            int[] cancelInt = {0, 0};
            messageVoiceCancel.getLocationInWindow(cancelInt);
            int messageVoiceCancelWidth = messageVoiceCancel.getWidth();  // {}
            int messageVoiceCancelHeight = messageVoiceCancel.getHeight();
            //获取退出的上右下左
            int messageVoiceCancel_left = cancelInt[0];
            int messageVoiceCancel_top = cancelInt[1];
            int messageVoiceCancel_right = messageVoiceCancel_left + messageVoiceCancelWidth;
            int messageVoiceCancel_bottom = messageVoiceCancel_top + messageVoiceCancelHeight;

            int[] toText = {0, 0};
            messageVoiceTotext.getLocationInWindow(toText);
            int messageVoiceTotextWidth = messageVoiceTotext.getWidth();
            int messageVoiceTotextHeight = messageVoiceTotext.getHeight();

            // 获取转文字的上右下左
            int messageVoiceTotext_left = toText[0];
            int messageVoiceTotext_top = toText[1];
            int messageVoiceTotext_right = messageVoiceTotext_left + messageVoiceTotextWidth;
            int messageVoiceTotext_bottom = messageVoiceTotext_top + messageVoiceTotextHeight;
            messageVoiceTotext.getLocationInWindow(toText);
            X = event.getRawX();
            Y = event.getRawY();
            //退出语音
            messageVoiceCancelBg.setVisibility(View.GONE);
            //文字识别
            messageVoiceTotextBg.setVisibility(View.GONE);
            //识别失败
            messageVoiceTexterrorBg.setVisibility(View.GONE);
            //发送语音
            messageVoiceSendvoiceBg.setVisibility(View.GONE);
            messageVoiceTotextContent.setVisibility(GONE);
            audiowaveview.setVisibility(VISIBLE);
            messageVoiceTotextUpdata.setVisibility(GONE);
            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                //开始录制
                //录制音频文件名
                voicePath = PathUtil.getInstance().getVoicePath() + "/" + EMClient.getInstance().getCurrentUser() + System.currentTimeMillis() + ".mp3";
                File file = new File(voicePath);
                mp3Recorder = new MP3Recorder(file);
                try {
                    mp3Recorder.start();
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (handler == null){
                                return;
                            }
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        int volume = mp3Recorder.getVolume();
                                        ALog.i("run", "run: " + (volume / 40));
                                        audiowaveview.setData((volume / 40));
                                        audiowaveview.notifityChangeData();
                                    } catch (Throwable throwable) {
                                        throwable.printStackTrace();
                                    }
                                }
                            });
                        }
                    },0,50);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                startTime = System.currentTimeMillis();
                messageVoiceTotextModule.setVisibility(View.GONE);
                messageVoiceTovoiceModule.setVisibility(View.VISIBLE);
                messageVoiceBottomBgIcon.setVisibility(View.VISIBLE);
                messageVoiceBottomBg.setVisibility(View.VISIBLE);
                messageVoiceSendvoiceBg.setVisibility(View.VISIBLE);
                voicePopWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                //判断移动的区域
                messageVoiceBottomTitle.setVisibility(View.INVISIBLE);
                messageVoiceTotextTitle.setVisibility(View.INVISIBLE);
                messageVoiceCancelTitle.setVisibility(View.INVISIBLE);
                if (X >= messageVoiceCancel_left && X <= messageVoiceCancel_right && Y >= messageVoiceCancel_top && Y <= messageVoiceCancel_bottom) {
                    //退出语音取消发送
                    Glide.with(v.getContext()).load(R.drawable.message_voice_cancel_select).into(messageVoiceCancel);
                    messageVoiceBottomBg.setBackground(v.getContext().getResources().getDrawable(R.drawable.message_voice_bottom_bg_unselect));
//                    Glide.with(mContext).load(R.drawable.message_voice_bottom_bg_unselect).transform(new CenterCrop()).into(messageVoiceBottomBg);
                    messageVoiceCancelTitle.setVisibility(View.VISIBLE);
                    messageVoiceCancelBg.setVisibility(View.VISIBLE);
                    messageVoiceSendvoiceBg.setVisibility(View.GONE);
                } else if (X >= messageVoiceTotext_left && X <= messageVoiceTotext_right && Y >= messageVoiceTotext_top && Y <= messageVoiceTotext_bottom) {
                    //文字识别
                    Glide.with(v.getContext()).load(R.drawable.message_voice_totext_select).into(messageVoiceTotext);
                    messageVoiceBottomBg.setBackground(v.getContext().getResources().getDrawable(R.drawable.message_voice_bottom_bg_unselect));
//                    Glide.with(mContext).load(R.drawable.message_voice_bottom_bg_unselect).transform(new CenterCrop()).into(messageVoiceBottomBg);
                    messageVoiceTotextTitle.setVisibility(View.VISIBLE);
                    messageVoiceSendvoiceBg.setVisibility(View.GONE);
                    messageVoiceTotextBg.setVisibility(View.VISIBLE);
                } else {
                    Glide.with(v.getContext()).load(R.drawable.message_voice_cancel).into(messageVoiceCancel);
                    Glide.with(v.getContext()).load(R.drawable.message_voice_totext).into(messageVoiceTotext);
                    messageVoiceBottomBg.setBackground(v.getContext().getResources().getDrawable(R.drawable.message_voice_bottom_bg));
//                    Glide.with(mContext).load(R.drawable.message_voice_bottom_bg).transform(new CenterCrop()).into(messageVoiceBottomBg);
                    messageVoiceBottomTitle.setVisibility(View.VISIBLE);
                    messageVoiceSendvoiceBg.setVisibility(View.VISIBLE);
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                //结束录制
                mp3Recorder.stop();
                mp3Recorder = null;
                timer.cancel();
                long l = System.currentTimeMillis() - startTime;
                voiceLength = (int) (l / 1000);
               if (X >= messageVoiceCancel_left && X <= messageVoiceCancel_right && Y >= messageVoiceCancel_top && Y <= messageVoiceCancel_bottom) {
                    //退出语音取消发送
                    File file = new File(voicePath);
                    if (file.exists()) {
                        file.delete();
                    }
                    voicePopWindow.dismiss();
                } else if (X >= messageVoiceTotext_left && X <= messageVoiceTotext_right && Y >= messageVoiceTotext_top && Y <= messageVoiceTotext_bottom) {
                   if (l < 1000) {
                       Toast.makeText(v.getContext(), "语音时间小于1秒", Toast.LENGTH_SHORT).show();
                       File file = new File(voicePath);
                       if (file.exists()) {
                           file.delete();
                       }
                       voicePopWindow.dismiss();
                       return false;
                   }
                       //文字识别
                    Glide.with(v.getContext()).load(R.drawable.message_voice_totext_select).into(messageVoiceTotext);
                   messageVoiceBottomBg.setBackground(v.getContext().getResources().getDrawable(R.drawable.message_voice_bottom_bg_unselect));
//                    Glide.with(mContext).load(R.drawable.message_voice_bottom_bg_unselect).transform(new CenterCrop()).into(messageVoiceBottomBg);
                    messageVoiceTotextModule.setVisibility(View.VISIBLE);
                    messageVoiceBottomBgIcon.setVisibility(View.GONE);
                    messageVoiceBottomBg.setVisibility(View.GONE);
                    messageVoiceTovoiceModule.setVisibility(View.GONE);
                    messageVoiceTotextBg.setVisibility(View.VISIBLE);
                    Glide.with(v.getContext()).load(R.drawable.message_voice_totext_ing).transform(new CenterCrop(), new CircleCrop()).into(messageVoiceTotextText);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    touchCallback.onToText(voicePath,(int) (l / 1000));
                } else {
                   if (l < 1000) {
                       Toast.makeText(v.getContext(), "语音时间小于1秒", Toast.LENGTH_SHORT).show();
                       File file = new File(voicePath);
                       if (file.exists()) {
                           file.delete();
                       }
                       voicePopWindow.dismiss();
                       return false;
                   }
                    //发送
                    touchCallback.onSuccess(voicePath, voiceLength);
                    voicePopWindow.dismiss();
                }
            }
            return false;
        }
    }


    public static class SendVoiceClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            voicePopWindow.dismiss();
        }
    }




    public interface TouchCallback {
        void onSuccess(String voicePath, int voiceLength);

        void onError();

        void onToText(String voicePath, int voiceLength);
    }

    public static void setToTextResult(boolean isEdit,String content){
        messageVoiceTotextContent.setText(content);
        messageVoiceTotextContent.setEnabled(isEdit);
    }

    public static String getToTextResult(){
        return messageVoiceTotextContent.getText().toString();
    }


    public static int getVoiceLength(){
        return voiceLength;
    }

    public static String getVoicePath(){
        return voicePath;
    }
}
